﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SmallERP.COM;
using SmallERP.MODEL.FoundationModel;
using SmallERP.Bll.PinBan;
using SmallERP.Bll.Com;
using SmallERP.DAL;
using FastReport;
using DevExpress.XtraEditors.Controls;
using SmallERP.MODEL.PaperManager;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Columns;
using SmallERP.Bll.MakeBigPic;
using SmallERP.Bll.BaseInfo;
//using SmallERP.Bll.PaperManage;

namespace SmallERP.PaperManange
{
    public partial class FrmMain : Form
    {
        /// <summary>
        /// 存放纸型
        /// </summary>
        private List<PaperType_Info> PTList;
        /// <summary>
        /// 存放纸面
        /// </summary>
        private List<PaperFace_Info> PFList;

        /// <summary>
        /// 存放打印机列表
        /// </summary>
        private List<Printer_info> PList;

        private MainBLL _mainBLL;
        Papertype paperTypeBll;
        Paperface paperfaceBll;
        PaperInfo_BLL paperinfobll;
        public FrmMain()
        {
            InitializeComponent();
            _mainBLL = new MainBLL(Properties.Settings.Default.ServerIP, Properties.Settings.Default.ServerPort);
            paperTypeBll = new Papertype();
            paperfaceBll = new Paperface();
            paperinfobll = new PaperInfo_BLL();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //充值管理页面的加载
            //labelControl2.Text = "当前剩余" + UnityMethod.GetUseableArea(Properties.Settings.Default.ServerIP, Properties.Settings.Default.ServerPort).ToString("0.0000") + "平米";
            //LinkCrushRecords();
            //btnOK.
            LoadPTFCmd();
            LoadPaperInfoList();
        }

        /// <summary>
        /// 加载纸型纸面下拉列表
        /// </summary>
        private void LoadPTFCmd()
        {
            if (PTList == null || PTList.Count < 1)
            {
                PTList = paperTypeBll.GetPaperTypeList();
            }
            if (PFList == null || PFList.Count < 1)
            {
                PFList = paperfaceBll.GetPaperFaceList();
            }

            cmbPT.DataSource = PTList;
            cmbPT.DisplayMember = "PaperTypeName";
            cmbPT.ValueMember = "PaperTypeId";

            cmbPF.DataSource = PFList;
            cmbPF.DisplayMember = "PaperFaceName";
            cmbPF.ValueMember = "PaperFaceId";
        }

        /// <summary>
        /// 加截库存纸列表
        /// </summary>
        private void LoadPaperInfoList()
        {
            List<PaperInfo_info> PList = new List<PaperInfo_info>();
            PList = paperinfobll.GetAllNotOverPaper();

            gcPaperInfo.DataSource = PList;
            label5.Text = "总数：" + PList.Count + "轴纸";
        }

        #region 库存管理
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text == "添加")
            {
                btnAdd.Text = "保存";
                gcMain.Enabled = true;
                LoadPTFCmd();
                txtNum.Enabled = true;
                txtLength.Value = 1;
                txtWidth.Value = 1;
                txtNum.Value = 1;

                btnModify.Enabled = false;
                btnDel.Enabled = false;
                btnCancel.Enabled = true;
            }
            else
            {
                List<PaperInfo_info> ListNew = new List<PaperInfo_info>();
                for (int i = 0; i < txtNum.Value; i++)
                {
                    ListNew.Add(new PaperInfo_info()
                    {
                        AddTime = DateTime.Now,
                        LastBordId = 0,
                        EndPaperLength = 0,
                        Length = (double)txtLength.Value,
                        Width = (double)txtWidth.Value,
                        LastPrintTime = DateTime.Now,
                        PaperTypeID = (int)cmbPT.SelectedValue,
                        PaperFaceName = cmbPF.Text,
                        PaperTypeName = cmbPT.Text,
                        PaperFaceID = (int)cmbPF.SelectedValue
                    });
                }
                List<int> newPaperCodeList = new List<int>();
                int result = paperinfobll.AddNewPaperInfo(ListNew, out newPaperCodeList);
                if (result == 0)//添加成功
                {
                    btnAdd.Text = "添加";
                    btnCancel.Enabled = false;
                    btnDel.Enabled = true;
                    btnModify.Enabled = true;
                    txtNum.Value = 1;
                    gcMain.Enabled = false;

                    LoadPaperInfoList();

                    FrmShowPaperCode frm = new FrmShowPaperCode();
                    frm.paperIdList = newPaperCodeList;
                    frm.ShowDialog();
                    //MessageBox.Show("添加成功");
                }
                else
                {
                    MessageBox.Show("添加失败");
                }
            }
        }

        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle > -1)
            {
                ShowMsgByIndex(e.FocusedRowHandle);
            }
        }

        void ShowSelectedPaperDetail()
        {
            foreach (var index in gvPaperInfo.GetSelectedRows())
            {
                ShowMsgByIndex(index);
            }
        }

        private PaperInfo_info _SelectedPaperInfo;
        void ShowMsgByIndex(int rowIndex)
        {
            PaperInfo_info p = (PaperInfo_info)gvPaperInfo.GetRow(rowIndex);
            _SelectedPaperInfo = p;
            if (p != null)
            {
                cmbPF.Text = p.PaperFaceName;
                cmbPT.Text = p.PaperTypeName;
                txtLength.Value = (decimal)p.Length;
                txtWidth.Value = (decimal)p.Width;
                txtNum.Value = 1;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            gcMain.Enabled = false;
            btnAdd.Text = "添加";
            btnAdd.Enabled = true;
            btnModify.Text = "修改";
            btnModify.Enabled = true;
            btnDel.Enabled = true;
            btnCancel.Enabled = false;
            ShowSelectedPaperDetail();
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            if (btnModify.Text == "修改")
            {
                if (_SelectedPaperInfo != null && _SelectedPaperInfo.Status != (int)SmallERP.COM.Status.PaperInfoStatus.Using)
                {
                    btnModify.Text = "保存";
                    gcMain.Enabled = true;
                    btnCancel.Enabled = true;
                    btnAdd.Enabled = false;
                    btnDel.Enabled = false;
                    txtNum.Enabled = false;

                    LoadPTFCmd();
                    ShowSelectedPaperDetail();
                }
                else
                {
                    MessageBox.Show("正在使用中的纸无法修改");
                }
            }
            else
            {
                btnModify.Text = "修改";
                btnCancel.Enabled = false;
                btnAdd.Enabled = true;
                btnDel.Enabled = true;
                gcMain.Enabled = false;

                _SelectedPaperInfo.PaperTypeID = (int)cmbPT.SelectedValue;
                _SelectedPaperInfo.PaperFaceID = (int)cmbPF.SelectedValue;
                _SelectedPaperInfo.Length = (double)txtLength.Value;
                _SelectedPaperInfo.Width = (double)this.txtWidth.Value;
                int result = paperinfobll.ModifyPaperInfo(_SelectedPaperInfo);
                if (result == 0)
                {
                    //成功
                    LoadPaperInfoList();
                    MessageBox.Show("更新成功");
                }
                else
                {
                    MessageBox.Show("更新失败");
                }

            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (_SelectedPaperInfo != null && _SelectedPaperInfo.Status != (int)SmallERP.COM.Status.PaperInfoStatus.Using)
            {
                if (MessageBox.Show("确认删除选中的纸？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    paperinfobll.DelPaper(_SelectedPaperInfo);
                    LoadPaperInfoList();
                    MessageBox.Show("删除成功");

                }
            }
            else
            {
                MessageBox.Show("正在使用中的纸无法删除");
            }
        }
        #endregion

        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (xtraTabControl1.SelectedTabPageIndex == 4)//充值管理
            {

            }
            else if (xtraTabControl1.SelectedTabPageIndex == 0)//入库管理
            {
                LoadPaperInfoList();
            }
            else if (xtraTabControl1.SelectedTabPageIndex == 1)//查看纸的使用统计信息
            {
                IniliQueryData();
            }
            else if (xtraTabControl1.SelectedTabPageIndex == 3)//查询返单记录
            {
                IntRebackForm();
            }
            this.Cursor = Cursors.Default;
        }
        #region 返工查询
        private List<User_Info> _userList;
        /// <summary>
        /// 初始化返工查询界面
        /// </summary>
        private void IntRebackForm()
        {
            BindUserList();
            InitDate();
        }
        /// <summary>
        /// 绑定用户列表,返单人、责任人
        /// </summary>
        private void BindUserList()
        {
            if (_userList == null || _userList.Count < 1)
            {
                _userList = UserBLL.GetAllUsers();
            }
            cmbCreateUser.Properties.DataSource = _userList;
            cmbCreateUser.Properties.DisplayMember = "UserName";

            cmbReponseUser.Properties.DataSource = _userList;
            cmbReponseUser.Properties.DisplayMember = "UserName";
        }

        /// <summary>
        /// 初始化界面上的时间控件
        /// </summary>
        private void InitDate()
        {
            deStart_R.DateTime = DateTime.Now.AddDays(-1);
            deEnd_R.DateTime = DateTime.Now;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            DateTime startTime = deStart_R.DateTime;
            DateTime endTime = deEnd_R.DateTime;
            List<string> CreateUserNameList = new List<string>(), ResponseUserNameList = new List<string>();
            foreach (var item in cmbCreateUser.Properties.Items)
            {
                CheckedListBoxItem a = ((CheckedListBoxItem)item);
                if (a.CheckState == CheckState.Checked)
                {
                    CreateUserNameList.Add(a.ToString());
                }
            }

            foreach (var item in cmbReponseUser.Properties.Items)
            {
                CheckedListBoxItem a = ((CheckedListBoxItem)item);
                if (a.CheckState == CheckState.Checked)
                {
                    ResponseUserNameList.Add(a.ToString());
                }
            }

            List<InnerReturn_Info> listResult = UserBLL.GetInnerReturnResult(startTime, endTime, CreateUserNameList, ResponseUserNameList);
            gcInnerReturn.DataSource = listResult;
            labelControl16.Text = "总面积：" + listResult.Sum(i => i.Area).ToString("0.0000") + " 平米";

            button2.Enabled = true;
            this.Cursor = Cursors.Default;
        }

        #endregion
        Printer printerbll = new Printer();
        #region 查看纸的使用情况
        /// <summary>
        /// 绑定打印机列表、纸型、纸面列表
        /// </summary>
        private void IniliQueryData()
        {
            //纸型、纸面
            if (PTList == null || PTList.Count < 1)
            {
                PTList = paperTypeBll.GetPaperTypeList();
            }
            if (PFList == null || PFList.Count < 1)
            {
                PFList = paperfaceBll.GetPaperFaceList();
            }

            cmbPT_Stat.Properties.DataSource = PTList;
            cmbPT_Stat.Properties.DisplayMember = "PaperTypeName";
            cmbPT_Stat.Properties.ValueMember = "PaperTypeId";

            cmbPF_Stat.Properties.DataSource = PFList;
            cmbPF_Stat.Properties.DisplayMember = "PaperFaceName";
            cmbPF_Stat.Properties.ValueMember = "PaperFaceId";

            //打印机
            if (PList == null || PList.Count < 1)
            {
                PList = printerbll.GetPrinterList();
            }
            cmbPrinter.Properties.DataSource = PList;
            cmbPrinter.Properties.DisplayMember = "PName";
            cmbPrinter.Properties.ValueMember = "PrinterID";

            deStart.DateTime = DateTime.Now.Date.AddDays(-1);
            deEnd.DateTime = DateTime.Now.Date;

        }

        private void gvPaperInfo_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle > -1)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            //打印选中纸的条码
            Report rp = new Report();
            rp.Load(Application.StartupPath + "\\Reports\\相纸条码.frx");
            rp.PrintSettings.ShowDialog = true;
            foreach (var index in gvPaperInfo.GetSelectedRows())
            {
                PaperInfo_info curPi = (PaperInfo_info)gvPaperInfo.GetRow(index);
                rp.SetParameterValue("pId", "*" + curPi.PrintPaperId + "*");
                rp.Print();
            }
        }

        private void gvPaperInfo_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                //PaperInfo_info curPi = (PaperInfo_info)gvPaperInfo.GetRow(e.RowHandle);
                //switch (curPi.Status)
                //{
                //    case 0:
                //        gvPaperInfo.getro(e.RowHandle, "Status", "未使用");
                //        break;
                //    case 1:
                //        gvPaperInfo.SetRowCellValue(e.RowHandle, "Status", "正在使用");
                //        break;
                //    default:
                //        break;
                //}
            }
        }

        private void gvPaperInfo_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {


        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.button1.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            //查询            
            List<int> SelectedPrinterIdList = new List<int>();
            List<int> SelectedPT = new List<int>();
            List<int> SelectedPF = new List<int>();

            foreach (var item in cmbPrinter.Properties.Items)
            {
                CheckedListBoxItem a = ((CheckedListBoxItem)item);
                if (a.CheckState == CheckState.Checked)
                {
                    SelectedPrinterIdList.Add((int)a.Value);
                }
            }
            foreach (var item in cmbPF_Stat.Properties.Items)
            {
                CheckedListBoxItem a = ((CheckedListBoxItem)item);
                if (a.CheckState == CheckState.Checked)
                {
                    SelectedPF.Add((int)a.Value);
                }
            }

            foreach (var item in cmbPT_Stat.Properties.Items)
            {
                CheckedListBoxItem a = ((CheckedListBoxItem)item);
                if (a.CheckState == CheckState.Checked)
                {
                    SelectedPT.Add((int)a.Value);
                }
            }

            if (SelectedPrinterIdList.Count < 1 || SelectedPT.Count < 1 || SelectedPF.Count < 1)
            {
                MessageBox.Show("请选择相应的打印机、纸型、纸面，不能为空");
                this.button1.Enabled = true;
                this.Cursor = Cursors.Default;
                return;
            }
            else
            {
                List<PaperInfo_Info> ListResult =paperinfobll.GetSomePaperUseStat(SelectedPrinterIdList, SelectedPT, SelectedPF, deStart.DateTime, deEnd.DateTime);
                gcUsePaper.DataSource = ListResult;


                foreach (GridColumn column in this.gvPaperInfo.Columns)
                {
                    column.BestFit();
                }
             


                //计算总的面积
                labelControl8.Text = "总面积：" + ListResult.Sum(p => p.TotalArea).ToString("0.0000") + "（㎡）";
                labelControl9.Text = "浪费总面积：" + ListResult.Sum(p => p.WrasteArea).ToString("0.0000") + "（㎡）";
                double a = (ListResult.Sum(p => p.WrasteArea) / ListResult.Sum(p => p.TotalArea));
                labelControl10.Text = "浪费百分比：" + (a * 100).ToString("0.00") + "%";
                labelControl11.Text = "有效百分比：" + ((1 - a) * 100).ToString("0.00") + "%";
                labelControl12.Text = "轴数：" + ListResult.Count;
            }

            this.button1.Enabled = true;
            this.Cursor = Cursors.Default;
        }

        private void gvUsePaperInfo_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.Column.VisibleIndex == 0 && view.IsMasterRowEmpty(e.RowHandle))
                (e.Cell as GridCellInfo).CellButtonRect = Rectangle.Empty;
        }

        private void gvUsePaperInfo_MasterRowGetRelationCount(object sender, MasterRowGetRelationCountEventArgs e)
        {
            e.RelationCount = 1;
        }

        private void gvUsePaperInfo_MasterRowGetRelationName(object sender, MasterRowGetRelationNameEventArgs e)
        {
            e.RelationName = "浪费明细";
        }

        private void gvUsePaperInfo_MasterRowGetChildList(object sender, MasterRowGetChildListEventArgs e)
        {
            GridView masterView = sender as GridView;
            if (e.RelationIndex == 0)
            {
                PaperInfo_Info master = masterView.GetRow(e.RowHandle) as PaperInfo_Info;
                if (master != null)
                {
                    e.ChildList = master.UseRecords;//select the required collection to show it in the detail view                    
                }
            }
        }
        #endregion

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //labelControl2.Text = "当前剩余" + UnityMethod.GetUseableArea(Properties.Settings.Default.ServerIP, Properties.Settings.Default.ServerPort).ToString("0.0000") + "平米";
        }
        #region 费纸确认
        List<PaperWasteRecord_info> viewList = new List<PaperWasteRecord_info>();
        PaperWasteRecordsBll _bll = new PaperWasteRecordsBll();
        private void textBoxPhotoBarCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == (int)Keys.Enter)
            {
                PaperWasteRecord_info info = new PaperWasteRecord_info();
                int wasteId = Convert.ToInt32(textBoxPhotoBarCode.Text.Trim());
                if (viewList.Count > 0)
                {
                    info = viewList.FirstOrDefault(p => p.Id == wasteId);
                    if (info == null)
                    {
                        viewList = _bll.MakeSureRecord(wasteId);
                    }
                    else
                    {
                        if (_bll.MakeSureRecordSinger(wasteId))
                        {
                            info.Status = (int)Status.WasterPaperStatus.Sure;
                        }
                        else
                        {

                        }

                    }
                }
                else
                {
                    viewList = _bll.MakeSureRecord(wasteId);
                    if (viewList.Count == 0)
                    {
                        MessageBox.Show("未找到记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                gridControlWasteView.DataSource = viewList;
                gridControlWasteView.RefreshDataSource();


            }
        }
        private void gridViewWasteView_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                PaperWasteRecord_info info = (PaperWasteRecord_info)gridViewWasteView.GetRow(e.RowHandle);
                if (info.Status == (int)Status.WasterPaperStatus.Sure)
                {
                    e.Appearance.BackColor = Color.LightGreen;
                }
            }
        }
        #endregion

        private void gridView2_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.RowHandle >= 0 && e.Column.Name == "PicPath")
            {
                int ret = CommonUtil.WinExec(@"explorer /n,/select," + e.CellValue.ToString(), 1);
            }
        }

        private void gvUsePaperInfo_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                PaperInfo_Info curP = (PaperInfo_Info)gvUsePaperInfo.GetRow(e.RowHandle);
                if (!curP.IsRight)
                {
                    e.Appearance.BackColor = Color.Red;
                }
            }
        }

        private void gvWrasteRecord_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                PaperRecords_Info rcorde = (PaperRecords_Info)gvWrasteRecord.GetRow(e.RowHandle);
                //string statusName = (string)gvWrasteRecord.GetRowCellValue(e.RowHandle, "StatusName");
                //statusName = gvWrasteRecord.GetRowCellDisplayText(e.RowHandle, "gridColumn24");
                if (rcorde != null)
                {
                    if (rcorde.Status == (int)SmallERP.COM.Status.WasterPaperStatus.Sure)
                    {
                        e.Appearance.BackColor = Color.Green;
                    }
                }

            }
        }

        private void gridView1_RowCountChanged(object sender, EventArgs e)
        {
            label5.Text = "总数：" + this.gvPaperInfo.RowCount + "轴纸";
            double totalArea = 0;

            for (int i = 0; i < gvPaperInfo.RowCount; i++)
            {
                SmallERP.MODEL.FoundationModel.PaperInfo_info pi = ((SmallERP.MODEL.FoundationModel.PaperInfo_info)gvPaperInfo.GetRow(i));
                totalArea += pi.Width*2.54/100 * pi.Length;
            }
            label10.Text = "总面积：" + totalArea.ToString("0.0000") + " 平方米";
        }

        private void btnCrush_Click(object sender, EventArgs e)
        {

            //float area =0;
            //int barcode =Convert.ToInt32(txtBarcode.Text);
            //string dogcode =_mainBLL.GetDogCode();
            //WS.WebServiceSoapClient webMethod = new SmallERP.PaperManange.WS.WebServiceSoapClient();
            //int ret = webMethod.WorkshopCrush(barcode, dogcode, out area);
            //if (ret == 0)
            //{
            //   int result =  _mainBLL.AddArea(area);
            //   if (result == 0)
            //   {
            //       CrushRecordInfo crInfo = new CrushRecordInfo();
            //       crInfo.Area = area;
            //       crInfo.CrushBarcode = barcode.ToString();
            //       crInfo.CrushTime = UnityMethod.GetSystemTime();
            //       crInfo.Overage = UnityMethod.GetUseableArea(Properties.Settings.Default.ServerIP, Properties.Settings.Default.ServerPort);
            //       int re = _mainBLL.InsertCrushRecord(crInfo);
            //       if (re == 0)
            //       {
            //           LinkCrushRecords();
            //       }
            //       else
            //       {
            //           WriteLogForCheck.WriteLogFile("插入充值记录失败 ，充值码为："+barcode+",面积为： "+area+"平米");
            //       }
            //       MessageBox.Show("充值成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //   }
            //   //else if (result == -1)
            //   //{
            //   //    MessageBox.Show("与服务端连接失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //   //}
            //   else
            //   {
            //       MessageBox.Show("与服务端连接失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //   }

               
            //}
            //else if (ret == -2)
            //{
            //    MessageBox.Show("充值码已使用或无效，请检查充值记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
            //else
            //{
            //    MessageBox.Show("网络服务连接失败","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            //}

        }

        /// <summary>
        /// 绑定充值记录
        /// </summary>
        private void LinkCrushRecords()
        {
            //gcCrushRecord.DataSource = _mainBLL.GetCrushRecordInfoList();
            //gcCrushRecord.RefreshDataSource();
        }

        private void txtWidth_EditValueChanged(object sender, EventArgs e)
        {

        }
    }
}
